import ScaleClass from './ScaleClass';
// import ExplainMap from '../../Game/ExplainMap';
import GameUtil from '../Util/GameUtil';

const LabelStatus = cc.Enum({
    'initial' : 1,      //初始状态 在线上
    'move' : 2,         //被单击 开始下落
    'return' : 3,       //被双击 回城
})


const {ccclass, property} = cc._decorator;

@ccclass
export default class LabelTouch extends cc.Component {

    // //触发选择事件
    // @property({
    //     type: cc.Component.EventHandler,
    //     displayName : '单击触发的事件',
    // })
    // clickEvent: cc.Component.EventHandler = null;
    // @property({
    //     type: cc.Component.EventHandler,
    //     displayName : '拖动触发的事件',
    // })
    // moveEvent: cc.Component.EventHandler = null;
    // @property({
    //     type: cc.Component.EventHandler,
    //     displayName : '双击触发的事件',
    // })
    // dbClickEvent: cc.Component.EventHandler = null;

    currScale : number = 1;
    initPos : cc.Vec2 = null;
    lastClickTime = null;
    currStatus = LabelStatus.initial;
    explainNode : cc.Node = null;
    moveSpeed : number = 400;
    isContact : boolean = false;
    parent;
    lineActive = true;
    lineScale;
    smallInterval = null;
    bigInterval = null;
    onLoad () {
        this.parent = this.node.parent;
        this.lineScale = this.parent.getChildByName("line").scaleX;
        //判断节点分组
        this.node.group = 'Label';
        //增加刚体
        let comp = this.node.addComponent(cc.RigidBody);
        comp.enabledContactListener = true;
        comp.bullet = true;
        comp.fixedRotation = true;
        //增加物理碰撞盒子
        let box = this.node.addComponent(cc.PhysicsBoxCollider);
        box.size = cc.size(this.node.width,this.node.height);


        //首先注册事件
        this.node.on(cc.Node.EventType.TOUCH_START, this.touchStart, this);
        this.node.on(cc.Node.EventType.TOUCH_MOVE, this.touchMove, this);
        this.node.on(cc.Node.EventType.TOUCH_CANCEL, this.touchEnd, this);
        this.node.on(cc.Node.EventType.TOUCH_END, this.touchEnd, this);

        //获取当前摄像机缩放尺寸
        let ScaleScript : ScaleClass =  cc.find('Canvas').getComponent('ScaleClass');
        this.currScale = ScaleScript.designScale;

        //获取节点默认坐标值
        this.initPos = this.node.position;

        //关闭重力以及物理碰撞检测体
        this.switchPhysics(false);

        //设置解释节点属性
        this.explainNode = this.node.parent.getChildByName('explain');
        this.explainNode.active = false;
        let title = this.node.getComponent(cc.Label).string;
        let exp = ExplainMap.readExplain(title);
        this.explainNode.getComponent(cc.Label).string = exp;
    }

    touchStart(event : cc.Event.EventTouch){
        Log('点击碰撞体',this.node.group)
        //初始状态不做处理
        if (this.currStatus == LabelStatus.initial || this.currStatus == LabelStatus.return){
            return;
        }
        //下面是移动状态

        //先关闭重力,不能关闭碰撞体
        let physicsBody = this.node.getComponent(cc.RigidBody);
        if (physicsBody){
            physicsBody.gravityScale = 0;
            physicsBody.linearVelocity = cc.v2(0,0);
        }
        if (this.lastClickTime == null){
            this.lastClickTime = new Date().getTime();
        }
        else{
            let tTime = new Date().getTime();
            let dis = tTime - this.lastClickTime;
            let second = dis/1000;
            if (second < 0.3){      //双击
                this.lastClickTime = null;
                this.moveToInitPos();
            }
            else{                   //超时,更新时间
                this.lastClickTime = tTime;
            }
        }
    }
    touchMove(event : cc.Event.EventTouch){
        //初始状态不做处理
        if (this.currStatus == LabelStatus.initial  || this.currStatus == LabelStatus.return){
            return;
        }
        if(this.isContact == true){
            Log('发生碰撞,停止move')
            return;
        }
        this.node.getComponent(cc.RigidBody).linearVelocity = cc.v2(0,0);
        //此时是移动状态,需要让节点跟随触摸点移动
        let dis = event.getDelta().div(this.currScale);
        let len = dis.mag();
        Log('len = ',len)
        if (len >= 20){
            dis = dis.mul(20 / len);
        }
        this.node.position = this.node.position.add(dis);
    }
    touchEnd(event : cc.Event.EventTouch){
        var self = this;
        //回归时间不做操作
        if (this.currStatus == LabelStatus.return){
            return;
        }
        //显示解释节点
        if (this.currStatus  == LabelStatus.initial){
            this.explainNode.active = true;
            //把线伸缩啊.....
            this.scale(1);
            cc.find("Canvas").getComponent(this.getScriptName()).updateExplain(this.parent);
            PlayEffect('人体配音/'+this.node.getComponent(cc.Label).string);
        }
        //其他初始状态做显示,掉下去操作
        //开启碰撞属性
        this.switchPhysics(true);
        //更改节点状态
        this.currStatus = LabelStatus.move;
    }

    scale(actionType){
        var self = this;
        let line = this.parent.getChildByName("line");
        let point = this.parent.getChildByName("point");

        let scaleSmall = function(){
            if(line.scaleX <= 0.1){
                line.scaleX = 0;
                point.active = false;
                clearInterval(self.smallInterval);
                self.lineActive = false;
            }else{
                line.scaleX -= 0.1;
            }
        }
        let scaleBig = function(){
            if(line.scaleX >= (self.lineScale-0.1)){
                line.scaleX = self.lineScale;
                clearInterval(self.bigInterval);
                self.lineActive = true;
            }else{
                point.active = true;
                line.scaleX += 0.1;
            }
        }
        if(actionType == 1 &&this.lineActive == true){
            self.smallInterval = setInterval(scaleSmall,50);

        }else if(actionType == 2 && this.lineActive == false){
            self.bigInterval = setInterval(scaleBig,50);
        }
    }


    // 只在两个碰撞体开始接触时被调用一次
    onBeginContact (contact, selfCollider, otherCollider) {
        Log('----------------------发生碰撞----------------------')
        this.isContact = true;

        
        // let node : cc.Node = otherCollider.node;
        // if (node.group != 'LabelBoard'){
        //     return;
        // }
        // if (node.x == 0){
        //     if (node.y > 0){        //上方

        //     }
        //     else if (node.y < 0){       //下方

        //     }
        // }
        // if (node.y == 0){
        //     if (node.x > 0){        //右方

        //     }
        //     else if (node.x < 0){       //左方

        //     }  
        // }
    }

    // 只在两个碰撞体结束接触时被调用一次
    onEndContact (contact, selfCollider, otherCollider) {
        Log('----------------------碰撞结束----------------------')
        this.isContact = false;
    }
    /**
     * 开关碰撞体
     * @param key  true/false
     */
    switchPhysics(key:boolean){
        let physicsBody = this.node.getComponent(cc.RigidBody);
        let physicsBox = this.node.getComponent(cc.PhysicsBoxCollider);
        if (key){
            //首先恢复重力,给一个向上的初始速度
            if (physicsBody){
                physicsBody.gravityScale = 1;
                physicsBody.linearVelocity = cc.v2(0,10);
            }
            //开启碰撞体
            if (physicsBox){
                physicsBox.enabled = true;
            }
        }
        else{
            if (physicsBody){
                physicsBody.gravityScale = 0;
                physicsBody.linearVelocity = cc.v2(0,0);
            }
            if (physicsBox){
                physicsBox.enabled = false;
            }
        }
    }
    /**
     * 移动节点到原始位置
     */
    moveToInitPos(){
        this.scale(2);
        //首先关闭碰撞体
        this.switchPhysics(false);
        //计算距离
        let cPos = this.node.position;
        let dis = cPos.sub(this.initPos).mag() * this.currScale;
        let time = dis / this.moveSpeed;
        this.currStatus = LabelStatus.return;
        this.node.runAction(cc.sequence(
            cc.moveTo(time,this.initPos),
            cc.callFunc(()=>{
                this.currStatus = LabelStatus.initial;
            })
        ))
    }

    getScriptName(){
        let sceneName = cc.director.getScene().name;
        let scriptName = '';
        if (sceneName == ''){
            sceneName = GameUtil.sceneName;
            Log('卧槽 我真是醉了,',sceneName)
        }
        switch(sceneName){
            case "NervousSystem":
                scriptName = "NervousManage";
                break;
            case 'SkeletalSystem':
                scriptName = "SkeletalManage";
                break;
            case 'BreatheScene':
                scriptName = "BreatheManager";
                break;
            case 'CirculatorySystem':
                scriptName = "CycleManage";
                break;
            case 'DigestiveSystem':
                scriptName = "DigestiveManage";
                break;
            case 'MuscleScene':
                scriptName = "MuscleManager";
                break;
            case 'ImmuneSystem':
                scriptName = "ImmuneManage";
                break;
            case 'SkinBody':
                scriptName = "SkinManage";
                break;
        }
        if (scriptName == ''){
            Log('查询场景出错  需要手动检测',sceneName);
        }
        return scriptName;
    }


}
